<template>
  <view class="container tab-bar">
    <scroll-view scroll-y>
      <view class="main">
        <!-- 头部搜索 -->
        <navigator
          url="../../pages/home/search"
          open-type="navigate"
          hover-class="none"
        >
          <view class="search-box">
            <text class="search-text">
              <text class="iconfont icon-search"></text>搜索任务名称
            </text>
          </view>
        </navigator>

        <!-- 中间内容 -->
        <view class="search-content">
          <view class="content-info">
            <view
              class="content-item"
              v-for="(item, index) in taskTypeList"
              :key="item.id"
              @longpress.stop="taskTypeLongPress($event, index)"
              @touchmove.stop="touchmove"
              @touchend.stop="touchend"
            >
              <navigator :url="'./task?uuid={{item.oid}}'" open-type="navigate">
                <view class="task-type-box">
                  <view
                    class="task-type-bg"
                    :style="{ 'background-color': item.option.color }"
                  ></view>

                  <image
                    class="item-icon"
                    :src="item.option.icon"
                    mode="widthFix"
                  />

                  <view class="item-text">
                    <text :style="{ color: item.option.color }">
                      {{ item.o_text }}
                    </text>
                    <text>{{ item.count }}</text>
                  </view>
                </view>
              </navigator>
            </view>

            <!-- 添加任务箱 -->
            <view class="content-item">
              <view class="add-task-box" @click.stop="isShowAddTaskType = true">
                <view
                  class="task-type-bg"
                  :style="{ 'background-color': '#333333' }"
                ></view>
                <span class="add-icon iconfont icon-add"></span>
                <text>添加任务箱</text>
              </view>
            </view>
          </view>
        </view>
      </view>
    </scroll-view>

    <!-- 拖拽盒子 -->
    <viw
      v-show="isShowDrag"
      class="drag-box"
      :style="{ top: dragY + 'px', left: dragX + 'px' }"
    >
      <view
        class="drag-bg"
        :style="{ 'background-color': dragInfo.option.bg_color }"
      ></view>

      <image class="drag-icon" :src="dragInfo.option.icon" mode="widthFix" />

      <view class="drag-text">
        <text :style="{ color: dragInfo.option.color }">
          {{ dragInfo.o_text }}
        </text>
        <text>
          {{ dragInfo.count }}
        </text>
      </view>
    </viw>

    <!-- 添加任务列表 -->
    <add-task-type
      v-show="isShowAddTaskType"
      v-on:closeAddTaskType="isShowAddTaskType = false"
      v-on:submitAddTaskType="submitAddTaskType"
    />

    <!-- 删除区域 -->
    <view
      v-show="isShowDelete"
      class="delete-box"
      :class="{ delConfirm: isConfirm }"
    >
      <text class="iconfont icon-shanchu"></text>
    </view>

    <!-- 是否确认 -->
    <confirm
      v-show="isShowConfirm"
      v-on:closeConfirm="
        this.isShowDelete = false;
        this.isShowConfirm = false;
      "
      v-on:deleteTask="deleteTaskType"
    />

    <TabBar v-show="!isShowDelete" :tabbar="tabbar" />
  </view>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import AddTaskType from "../../component/AddTaskType/AddTaskType";
import Confirm from "../../component/Confirm/Confirm";
import TabBar from "../../component/TabBar/TabBar";
// 引入接口文件
const {
  countWork,
  getWorksByOp,
  addOp,
  delOp,
} = require("../../api/home/home");

export default {
  props: {},
  components: { TabBar, AddTaskType, Confirm },
  data() {
    return {
      isShowDrag: false, // 是否显示拖拽盒子
      isMove: false, //是否可拖拽
      // 盒子移动距离
      dragX: 0,
      dragY: 0,
      // 移动元素的宽高
      dragWidth: 0,
      dragHeight: 0,
      // 父元素距离屏幕顶部的距离
      offsetX: 0,
      offsetY: 0,
      // 拖拽盒子信息
      dragInfo: {},
      isShowAddTaskType: false, // 是否显示添加任务类别
      isShowDelete: false, // 是否显示删除区域
      delAreaY: 0, // 删除区域Y轴坐标
      isConfirm: false,
      isShowConfirm: false,
    };
  },
  computed: {
    ...mapState(["tabbar", "taskTypeList", "isGetDataAgain"]),
  },
  watch: {},
  methods: {
    ...mapMutations(["editTabbar", "editTaskTypeList", "editIsGetDataAgain"]),

    // 获取任务列表
    getTaskList() {
      countWork({ code: uni.getStorageSync("openId") }).then(
        res => {
          this.editTaskTypeList(res);
        },
        err => {
          uni.showToast({ title: err, icon: "none" });
        }
      );
    },
    // 添加任务分类
    submitAddTaskType(params) {
      addOp(params).then(
        res => {
          uni.showToast({ title: "添加成功！", icon: "success" });
          // 刷新
          countWork({ code: uni.getStorageSync("openId") }).then(res => {
            this.editTaskTypeList(res);
          });
        },
        err => {
          uni.showToast({ title: err, icon: "none" });
        }
      );
      this.isShowAddTaskType = false;
    },
    // 删除任务分类
    deleteTaskType() {
      // 删除验证
      getWorksByOp({
        opid: this.dragInfo.oid,
        code: uni.getStorageSync("openId"),
      })
        .then(
          res => {
            let flag = false;
            res ? (flag = false) : (flag = true);
            return flag;
          },
          err => {
            uni.showToast({ title: err, icon: "none" });
            return false;
          }
        )
        .then(res => {
          if (res) {
            let params = {
              code: uni.getStorageSync("openId"),
              wcid: this.dragInfo.wcid,
            };
            delOp(params).then(
              res => {
                // 刷新
                countWork({ code: uni.getStorageSync("openId") }).then(res => {
                  this.editTaskTypeList(res);
                  uni.showToast({ title: "删除成功！", icon: "success" });
                });
              },
              err => {
                uni.showToast({ title: err, icon: "none" });
              }
            );
          } else {
            uni.showToast({ title: "该分类有任务，不能删除！", icon: "none" });
          }
        });

      this.isShowDelete = false; // 隐藏删除区域
      this.isShowConfirm = false;
    },
    // 长按任务分类
    taskTypeLongPress(e, index) {
      const query = uni.createSelectorQuery().in(this);
      query
        .selectAll(".task-type-box")
        .boundingClientRect(dom => {
          this.dragWidth = dom[index].width / 2;
          this.dragHeight = dom[index].height / 2;
        })
        .exec();
      this.dragX = e.currentTarget.offsetLeft + this.offsetX;
      this.dragY = e.currentTarget.offsetTop + this.offsetY;
      // 如果 index 是奇数那就 +5 px
      this.dragX += index % 2 == 0 ? 0 : 5;
      this.dragInfo = this.taskTypeList[index]; // 任务信息
      this.dragInfo.option.bg_color = this.taskTypeList[index].option.color;
      this.isShowDrag = true;
      this.isMove = true; // 开启拖拽
      this.isShowDelete = true; // 显示删除区域
      uni.vibrateShort(); // 开启手机震动
      this.isConfirm = false;
    },
    // 手指按住移动
    touchmove(e) {
      // 判断是否有长按
      if (!this.isMove) return;
      // 当前选中的元素距离父元素left、top距离  用于计算出手指移动距离
      const dragx = e.currentTarget.offsetLeft;
      const dragy = e.currentTarget.offsetTop;
      // 当前手指在屏幕中的x、y轴坐标 - 当前选中的元素距离父元素left、top距离
      // x、y:是让移动的盒子左上角和手指的位置保持一致
      const x = e.touches[0].pageX - e.currentTarget.offsetLeft - this.offsetX;
      const y = e.touches[0].pageY - e.currentTarget.offsetTop - this.offsetY;
      /* 移动的距离 = 元素距离父元素left、top距离 +
      （当前手指在屏幕中的x、y轴坐标 -
      容器元素距离页面top、left的距离 -
      当前元素本身宽度、高度的一半）*/
      this.dragX = dragx + (x - this.dragWidth);
      this.dragY = dragy + y;

      // 样式相关
      if (e.touches[0].pageY > this.delAreaY) {
        this.isConfirm = true;
        this.dragInfo.option.bg_color = "red";
      } else {
        this.isConfirm = false;
        this.dragInfo.option.bg_color = this.dragInfo.option.color;
      }
    },
    // 手指离开
    touchend() {
      if (!this.isMove) return;
      this.isShowConfirm = this.isConfirm;
      this.isShowDelete = this.isConfirm; // 隐藏删除区域
      this.isShowDrag = false; // 隐藏拖拽盒子
      this.isMove = false; // 关闭拖拽
    },
  },
  beforeCreate() {},
  onLoad() {
    // 设置TabBar
    this.editTabbar();
    // 获取任务列表
    this.getTaskList();
  },
  onShow() {
    // 是否要重新获取首页数据
    if (this.isGetDataAgain) {
      try {
        this.getTaskList();
      } catch (error) {
        console.log(error);
      } finally {
        this.editIsGetDataAgain(false);
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      const query = uni.createSelectorQuery().in(this);
      query
        .select(".content-info")
        .boundingClientRect(dom => {
          this.offsetX = dom.left;
          this.offsetY = dom.top;
        })
        .exec();
      query
        .select(".delete-box")
        .boundingClientRect(dom => {
          this.delAreaY = dom.top;
        })
        .exec();
    });
  },
  beforeDestroy() {},
};
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  background-color: #fff;

  .main {
    padding: 20rpx 40rpx 0 40rpx;

    // 头部搜索
    .search-box {
      margin: 20rpx 0;
      .search-text {
        display: block;
        width: 100%;
        height: 72rpx;
        margin: 10rpx 0;
        padding-left: 20rpx;
        line-height: 72rpx;
        background-color: #f2f2f2;
        border-radius: 8rpx;
        // text-align: center;
        font-size: 28rpx;
        color: #999999;
      }

      text {
        padding-right: 10rpx;
      }
    }

    // 中间内容
    .search-content {
      margin-top: 10rpx;

      .content-info {
        position: relative;
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 30rpx;

        // 任务列表
        .content-item {
          width: 50%;
          height: 280rpx;
          padding: 10rpx 0;
          overflow: hidden;

          // 选中奇数的元素
          &:nth-child(odd) {
            padding-right: 10rpx;
          }

          // 选中偶数的元素
          &:nth-child(even) {
            padding-left: 10rpx;
          }

          .task-type-box {
            position: relative;
            height: 100%;
            padding: 30rpx;
            border-radius: 16rpx;
            overflow: hidden;

            .item-icon {
              position: relative;
              display: block;
              width: 96rpx;
              height: 96rpx;
              margin-bottom: 64rpx;
              z-index: 1;
            }

            .item-text {
              position: relative;
              display: flex;
              justify-content: space-between;
              height: 40rpx;
              font-size: 28rpx;
              font-family: PingFang SC;
              font-weight: 500;
              line-height: 40rpx;
              z-index: 1;
            }
          }

          // 添加任务
          .add-task-box {
            position: relative;
            display: flex;
            align-items: center;
            height: 128rpx;
            padding-left: 40rpx;
            border-radius: 16rpx;
            overflow: hidden;
            font-size: 28rpx;
            font-family: PingFang SC;
            font-weight: 500;
            color: #333333;

            .add-icon {
              margin-right: 30rpx;
              color: #333333;
              font-size: 42rpx;
            }
          }

          & span,
          & text {
            position: relative;
            z-index: 1;
          }

          .task-type-bg {
            position: absolute;
            top: 0;
            right: 0;
            bottom: 0;
            left: 0;
            opacity: 0.1;
          }
        }
      }
    }
  }

  // 拖拽盒子
  .drag-box {
    box-sizing: border-box;
    position: absolute;
    top: 0;
    left: 0;
    width: 43.8%;
    height: 260rpx;
    padding: 30rpx;
    margin-top: 10rpx;
    border-radius: 16rpx;
    overflow: hidden;
    z-index: 10;

    .drag-bg {
      position: absolute;
      top: 0;
      right: 0;
      bottom: 0;
      left: 0;
      opacity: 0.1;
    }

    .drag-icon {
      position: relative;
      display: block;
      width: 96rpx;
      height: 96rpx;
      margin-bottom: 64rpx;
      z-index: 1;
    }

    .drag-text {
      position: relative;
      display: flex;
      justify-content: space-between;
      height: 40rpx;
      padding-right: 4rpx;
      font-size: 28rpx;
      font-family: PingFang SC;
      font-weight: 500;
      line-height: 40rpx;
      z-index: 1;
    }
  }

  // 删除
  .delete-box {
    position: fixed;
    left: 0;
    bottom: 0;
    width: 100%;
    height: 120rpx;
    background-color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1;
  }

  .delConfirm {
    color: red;
  }
}
</style>
